package com.logistics.service.impl;

import com.logistics.common.Result;
import com.logistics.entity.User;
import com.logistics.mapper.UserMapper;
import com.logistics.service.UserService;
import com.logistics.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public Result register(User user) {
        // 检查用户名是否已存在
        User existUser = userMapper.findByUsername(user.getUsername());
        if (existUser != null) {
            return Result.error("用户名已存在");
        }
        
        // 加密密码
        user.setPassword(PasswordUtil.encrypt(user.getPassword()));
        
        // 保存用户
        userMapper.insert(user);
        return Result.success();
    }

    @Override
    public Result login(String username, String password) {
        // 查询用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 验证密码
        if (!PasswordUtil.verify(password, user.getPassword())) {
            return Result.error("密码错误");
        }
        
        // 清除密码
        user.setPassword(null);
        return Result.success(user);
    }

    @Override
    public Result getUser(Long id) {
        User user = userMapper.findById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        user.setPassword(null);
        return Result.success(user);
    }

    @Override
    public Result listUsers() {
        List<User> users = userMapper.findAll();
        users.forEach(user -> user.setPassword(null));
        return Result.success(users);
    }

    @Override
    @Transactional
    public Result updateUser(User user) {
        // 检查用户是否存在
        User existUser = userMapper.findById(user.getId());
        if (existUser == null) {
            return Result.error("用户不存在");
        }
        
        // 如果修改了密码，需要加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(PasswordUtil.encrypt(user.getPassword()));
        } else {
            user.setPassword(existUser.getPassword());
        }
        
        userMapper.update(user);
        return Result.success();
    }

    @Override
    @Transactional
    public Result deleteUser(Long id) {
        // 检查用户是否存在
        User user = userMapper.findById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        userMapper.delete(id);
        return Result.success();
    }
} 